package com.androidviewbadge

import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.text.TextUtils
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
object AppToast {
    /**
     * 显示 Toast
     * @param message 提示信息
     */
    @JvmStatic
    fun show(context: Context,message: String?) {
        show(context,if (TextUtils.isEmpty(message)) "" else message, Toast.LENGTH_SHORT)
    }

    /**
     * 显示 Toast
     * @param message 提示信息
     * @param duration 显示时间长短
     */
    fun show(context: Context,message: String?, duration: Int) {
        val toast = Toast(context)
        toast.duration = duration
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.view = createTextToastView(context,message ?: "")
        toast.show()
    }

    /**
     * 创建自定义 Toast View
     *
     * @param message 文本消息
     * @return View
     */
    private fun createTextToastView(context: Context,message: String): View {
        // 画圆角矩形背景
        val rc = dp2px(context,3f).toFloat()
        val shape = RoundRectShape(floatArrayOf(rc, rc, rc, rc, rc, rc, rc, rc), null, null)
        val drawable = ShapeDrawable(shape)
        //        drawable.getPaint().setColor(Color.argb(225, 240, 240, 240));
        //背景颜色
        drawable.paint.color = Color.argb(204, 0, 0, 0)
        //0, 0, 0, 0.8
        drawable.paint.style = Paint.Style.FILL
        drawable.paint.isAntiAlias = true
        drawable.paint.flags = Paint.ANTI_ALIAS_FLAG
        // 创建View
        val layout = FrameLayout(context)
        val layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        layout.layoutParams = layoutParams
        layout.setPadding(dp2px(context,16f), dp2px(context,12f), dp2px(context,16f), dp2px(context,12f))
        layout.background = drawable
        // 创建TextView
        val textView = TextView(context)
        textView.layoutParams = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14f)
        textView.text = message
        textView.setLineSpacing(dp2px(context,4f).toFloat(), 1f)
        textView.setTextColor(Color.WHITE)
        layout.addView(textView)
        return layout
    }

    private fun dp2px(context: Context,dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }
}